#include "movetofront.h"

void MoveToFront::Encode( PBYTE buffer, DWORD cb )
{
	BYTE  byTbl[256];

	// initialize table
	for ( UINT u = 0; u < 256; u++ )
		byTbl[u] = u;

	// process input buffer
	for ( UINT c = 0; c < cb; c++ )
	{
		// find symbol in table
		for ( UINT i = 0; ; i++ )
			if ( byTbl[i] == *buffer )
				break;

		UINT index = i;

		// move table items til index by 1 position
		for ( ; i != 0; --i )
			byTbl[i] = byTbl[i - 1];

		byTbl[0] = *buffer;
		*buffer  = index;

		// inc ptr
		++buffer;
	}

	return;
}

void MoveToFront::Decode( PBYTE buffer, DWORD cb )
{
	BYTE  byTbl[256];

	// initialize table
	for ( UINT u = 0; u < 256; u++ )
		byTbl[u] = u;

	// process input buffer
	for ( UINT c = 0; c < cb; c++ )
	{
		BYTE by = byTbl[*buffer];

		// move table items til index by 1 position
		for ( UINT i = *buffer ; i != 0; --i )
			byTbl[i] = byTbl[i - 1];

		byTbl[0] = by;
		*buffer  = by;

		// inc ptr
		++buffer;
	}

	return;
}